package com.tjec.project.mdmSynchronous.service.impl;

import java.util.*;

import com.tjec.common.constant.Constants;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.project.mdmSynchronous.api.JSONUtils;
import com.tjec.project.mdmSynchronous.api.ThreadPost;
import com.tjec.project.mdmSynchronous.dao.ProjectLeaderDao;
import com.tjec.project.mdmSynchronous.service.MdmService;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsLeaderMember;
import com.tjec.project.projectLeaderWorkbeanch.mapper.BmsLeaderMemberMapper;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsLeaderMemberService;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.service.IBmsProjectService;
import com.tjec.project.system.domain.SysRole;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.domain.SysUserRole;
import com.tjec.project.system.mapper.SysUserMapper;
import com.tjec.project.system.mapper.SysUserRoleMapper;
import com.tjec.project.system.service.ISysRoleService;
import com.tjec.project.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tjec.project.mdmSynchronous.mapper.BmsProjectLeaderMapper;
import com.tjec.project.mdmSynchronous.domain.BmsProjectLeader;
import com.tjec.project.mdmSynchronous.service.IBmsProjectLeaderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

/**
 * 项目负责人Service业务层处理
 * 
 * @author villwang
 * @date 2020-05-25
 */
@Service
public class BmsProjectLeaderServiceImpl implements IBmsProjectLeaderService 
{
    private static final Logger log = LoggerFactory.getLogger(BmsProjectLeaderServiceImpl.class);
    @Autowired
    private BmsProjectLeaderMapper bmsProjectLeaderMapper;
    @Autowired
    private ProjectLeaderDao projectLeaderDao;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private IBmsProjectService bmsProjectService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IBmsLeaderMemberService bmsLeaderMemberService;

    @Autowired
    private BmsLeaderMemberMapper bmsLeaderMemberMapper;

    /**
     * 查询项目负责人
     * 
     * @param guid 项目负责人ID
     * @return 项目负责人
     */
    @Override
    public BmsProjectLeader selectBmsProjectLeaderByGuid(String guid)
    {
        return bmsProjectLeaderMapper.selectBmsProjectLeaderByGuid(guid);
    }

    /**
     * 查询项目负责人列表
     * 
     * @param bmsProjectLeader 项目负责人
     * @return 项目负责人
     */
    @Override
    public List<BmsProjectLeader> selectBmsProjectLeaderList(BmsProjectLeader bmsProjectLeader)
    {
        return bmsProjectLeaderMapper.selectBmsProjectLeaderList(bmsProjectLeader);
    }

    /**
     * 新增项目负责人
     * 
     * @param bmsProjectLeader 项目负责人
     * @return 结果
     */
    @Override
    public int insertBmsProjectLeader(BmsProjectLeader bmsProjectLeader)
    {
        return bmsProjectLeaderMapper.insertBmsProjectLeader(bmsProjectLeader);
    }

    /**
     * 修改项目负责人
     * 
     * @param bmsProjectLeader 项目负责人
     * @return 结果
     */
    @Override
    public int updateBmsProjectLeader(BmsProjectLeader bmsProjectLeader)
    {
        return bmsProjectLeaderMapper.updateBmsProjectLeader(bmsProjectLeader);
    }


    /**
     * 批量删除项目负责人
     * 
     * @param guids 需要删除的项目负责人ID
     * @return 结果
     */
    @Override
    public int deleteBmsProjectLeaderByGuids(String[] guids)
    {
        return bmsProjectLeaderMapper.deleteBmsProjectLeaderByGuids(guids);
    }

    /**
     * 删除项目负责人信息
     * 
     * @param guid 项目负责人ID
     * @return 结果
     */
    @Override
    public int deleteBmsProjectLeaderByGuid(String guid)
    {
        return bmsProjectLeaderMapper.deleteBmsProjectLeaderByGuid(guid);
    }
    /**
     *
     *@describe  查询第三方项目负责人
     *@params [userName, jobNo]
     *@return java.util.List<com.tjec.project.system.domain.SysUser>
     *@author VillWang
     *@date 2020/5/22
     *@other
     *
     */
    @Override
    public void synchronous(long max) {
        try {
            //获取最大时间戳
            List<Map<String, Object>> projectLeaderList = projectLeaderDao.getProjectLeaderList(max);
            List<BmsProjectLeader> list = this.dealWith(projectLeaderList);
            //处理数据
        /*for (BmsProjectLeader bmsProjectLeader:list) {
            String userGlobalid= bmsProjectLeader.getUserGlobalid();
            BmsProjectLeader bms2=  bmsProjectLeaderMapper.selectBmsProjectLeaderByUserglobalId(userGlobalid);
            if(bms2==null||bms2.equals("")){
               //插入数据
                bmsProjectLeader.setGuid(UUID.randomUUID().toString());
                bmsProjectLeaderMapper.insertBmsProjectLeader(bmsProjectLeader);
            }else {
                bmsProjectLeaderMapper.updateBmsProjectLeader(bmsProjectLeader);
                //同步修改项目负责人对用用户信息
                synProjectLeaderToSysUser(bmsProjectLeader);
            }
        }*/
            insertOrUpdateProjectLeader(list);

        } catch (Exception e) {
            log.error("项目负责人同步失败，详细信息："+e);
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 处理从接口中取出的项目负责人
     * @param list
     */
    @Transactional
    public void insertOrUpdateProjectLeader(List<BmsProjectLeader> list){
        for (BmsProjectLeader bmsProjectLeader : list) {
            try {
//                List<BmsProjectLeader> oldBmsProjectLeaders = bmsProjectLeaderMapper.selectBmsProjectLeaderByUserglobalId(bmsProjectLeader.getUserGlobalid());
                BmsProjectLeader oldBmsProjectLeaders = bmsProjectLeaderMapper.selectBmsProjectLeaderByGlobalId(bmsProjectLeader.getGlobalid());
                synProjectLeaderToSysUser(bmsProjectLeader);
                //是否存在原项目负责人
                if(null==oldBmsProjectLeaders){
                    //插入数据
                    bmsProjectLeader.setGuid(UUID.randomUUID().toString());
                    bmsProjectLeaderMapper.insertBmsProjectLeader(bmsProjectLeader);
                }else{
                    bmsProjectLeaderMapper.updateBmsProjectLeaderByGlobalid(bmsProjectLeader);
                    /*for (BmsProjectLeader oldBmsProjectLeader : oldBmsProjectLeaders) {
                        //判断项目负责人代码是否变化
                        if(ObjectUtils.nullSafeEquals(bmsProjectLeader.getLeadNo(), oldBmsProjectLeaders.getLeadNo())){
                            bmsProjectLeaderMapper.updateBmsProjectLeaderByUserGlobalid(bmsProjectLeader);
                        }else{
                            //插入数据
                            bmsProjectLeader.setGuid(UUID.randomUUID().toString());
                            bmsProjectLeaderMapper.insertBmsProjectLeader(bmsProjectLeader);
                        }
                    }*/
                }
            } catch (Exception e) {
                log.error("处理项目负责人数据失败，详细信息："+e);
                e.printStackTrace();
            }
            /*if(null==oldBmsProjectLeader){
                synProjectLeaderToSysUser(bmsProjectLeader);
                //插入数据
                bmsProjectLeader.setGuid(UUID.randomUUID().toString());
                bmsProjectLeaderMapper.insertBmsProjectLeader(bmsProjectLeader);
            }else{
                //查询该用户在用户表中是否存在
                SysUser user = new SysUser();
                user.setGlobalId(bmsProjectLeader.getUserGlobalid());
                SysUser sysUser = sysUserService.selectUserByUser(user);
                //判断UserGlobalid是否变化
                if(bmsProjectLeader.getUserGlobalid().equals(oldBmsProjectLeader.getUserGlobalid())){
                    if(bmsProjectLeader.getLeadNo().equals(oldBmsProjectLeader.getLeadNo())){
                        //同步更新项目表中的项目负责人代码
                        bmsProjectService.updateBmsProjectLeaderNoByProjectLeader(sysUser.getUserId(),bmsProjectLeader.getLeadNo());
                    }
                }else{
                    if(null==sysUser){
                        String roleId = sysRoleService.selectRoleByRoleKey(Constants.ROLE_PROJECT_LEADER_KEY).getRoleId();
                        //删除原用户项目负责人角色
                        SysUserRole sysUserRole = new SysUserRole();
                        sysUserRole.setUserId(sysUser.getUserId());
                        sysUserRole.setRoleId(roleId);
                        sysUserRoleMapper.deleteUserRoleInfo(sysUserRole);
                    }
                    synProjectLeaderToSysUser(bmsProjectLeader);
                }
                bmsProjectLeaderMapper.updateBmsProjectLeader(oldBmsProjectLeader);
            }*/
        }
    }

    /**
     * 取不在用户表中的项目负责人
     * @param bmsProjectLeader
     * @return
     */
    @Override
    public List<BmsProjectLeader> selectBmsProjectLeaderNotSysUser(BmsProjectLeader bmsProjectLeader) {
        return bmsProjectLeaderMapper.selectBmsProjectLeaderNotSysUser(bmsProjectLeader);
    }


    /**
     *
     *@describe
     *@params []
     *@return java.util.List<>
     *@author VillWang
     *@date 2020/5/14
     *@other
     *
     */
    public List<BmsProjectLeader> dealWith(List<Map<String, Object>> list)throws Exception{
        List<BmsProjectLeader> bList=new ArrayList<BmsProjectLeader>();
        for (Map<String, Object> map:list) {
            BmsProjectLeader bmsProjectLeader =  new BmsProjectLeader();
            bmsProjectLeader.setGlobalid((String) map.get("globalId"));
            bmsProjectLeader.setUserGlobalid((String) map.get("userGlobalId"));
            bmsProjectLeader.setUserName((String) map.get("userName"));
            bmsProjectLeader.setJobNo((String) map.get("jobNo"));
            bmsProjectLeader.setLeadNo((String) map.get("leadNo"));
            bmsProjectLeader.setTimeStamp(String.valueOf(map.get("timestamp")));
            bmsProjectLeader.setFlag((String) map.get("flag"));
            bList.add(bmsProjectLeader);
        }
        return bList;
    }

    /**
     * 同步项目负责人信息到用户表，如果是新用户，需配置项目负责人角色
     */
    @Transactional
    public void synProjectLeaderToSysUser(BmsProjectLeader bmsProjectLeader){
        if(StringUtils.isBlank(bmsProjectLeader.getUserGlobalid())){
            return;
        }
        //查询该用户在用户表中是否存在
        SysUser user = new SysUser();
        user.setGlobalId(bmsProjectLeader.getUserGlobalid());
        SysUser sysUser = sysUserService.selectUserByUser(user);
        if(sysUser==null){
            //sysUser.setPhonenumber(bmsProjectLeader.getPhoneNumber());
            //sysUser.setPersonnelDept(bmsProjectLeader.getPersonnelDept());
//            sysUser.setUserName(bmsProjectLeader.getUserName());
//            sysUser.setJobNo(bmsProjectLeader.getJobNo());
//            sysUser.setPassword(SecurityUtils.encryptPassword(Constants.INITIAL_PASSWORD));
//            sysUser.setRoleIds(new String[]{roleId});
//            sysUserService.insertUser(sysUser);
        }else{
            //查询项目负责人所对应ID
            String roleId = sysRoleService.selectRoleByRoleKey(Constants.ROLE_PROJECT_LEADER_KEY).getRoleId();
            //是否包含项目负责人角色，不包含，增添加项目负责人角色
            if(!CollectionUtils.isEmpty(sysUser.getRoles())){
                List<String> roleIds =  new ArrayList<>();
                for (SysRole sysRole : sysUser.getRoles()) {
                    roleIds.add(sysRole.getRoleGuid());
                }
                if(!roleIds.contains(roleId)){
                    roleIds.add(roleId);
                }
                String[] strings = new String[roleIds.size()];
                roleIds.toArray(strings);
                sysUser.setRoleIds(strings);
            }
            //暂时修改用户名和员工编号
            sysUser.setNickName(bmsProjectLeader.getUserName());
            sysUser.setJobNo(bmsProjectLeader.getJobNo());
            sysUserService.updateUser(sysUser, true);
            //如果为项目负责人，添加自己到人员清单表中
            BmsLeaderMember newBmsLeaderMember = new BmsLeaderMember();
            newBmsLeaderMember.setLeader(sysUser.getUserId());
            newBmsLeaderMember.setUserId(sysUser.getUserId());
            List<BmsLeaderMember> bmsLeaderMembers = bmsLeaderMemberService.selectBmsLeaderMemberList(newBmsLeaderMember);
            if (CollectionUtils.isEmpty(bmsLeaderMembers)) {
                //默认设置为0=成员
                newBmsLeaderMember.setRole("0");
                newBmsLeaderMember.setCreateTime(DateUtils.getNowDate());
                newBmsLeaderMember.setGuid(UUID.randomUUID().toString());
                bmsLeaderMemberMapper.insertBmsLeaderMember(newBmsLeaderMember);
            }
            //同步更新项目表中的项目负责人代码
//            bmsProjectService.updateBmsProjectLeaderNoByProjectLeader(sysUser.getUserId(),bmsProjectLeader.getLeadNo());
        }
    }
}
